package cn.ecasoft.controller;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: LiangChun
 * @Description: demo
 * @DateTime: 2023/2/23
 **/
public class DoSomeThing implements Runnable {
    private Socket socket;

    public DoSomeThing(Socket socket) {
        this.socket = socket;
    }

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8888);
            System.out.println("启动服务器....");
            while (true){
                Socket client = ss.accept();
                new Thread(new DoSomeThing(client)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        System.out.println("连接成功," + socket.getInetAddress() + "，当前线程：" + Thread.currentThread().getName());
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String receiveMsg = bufferedReader.readLine();
            System.out.println("服务端收到消息：" + receiveMsg);
            bufferedWriter.write("测试，李志威要求换一条数据\r");
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
